var MongoDB = require('mongodb').Db;
var Server = require('mongodb').Server;
var moment = require('moment');

/*
 ESTABLISH DATABASE CONNECTION
 */

var dbName = process.env.DB_NAME || 'node-login';
var dbHost = process.env.DB_HOST || 'localhost';
var dbPort = process.env.DB_PORT || 27017;

var db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});
db.open(function (e, d) {
    if (e) {
        console.log(e);
    } else {
        if (process.env.NODE_ENV == 'live') {
            db.authenticate(process.env.DB_USER, process.env.DB_PASS, function (e, res) {
                if (e) {
                    console.log('mongo :: error: not authenticated', e);
                }
                else {
                    console.log('mongo :: authenticated and connected to database :: "' + dbName + '"');
                }
            });
        } else {
            console.log('mongo :: connected to database :: "' + dbName + '"');
        }
    }
});

var weathers = db.collection('weathers');


// 每次更新时删除之前的天气， 只保留未来五天的天气
exports.updateWeathers = function (weatherList, callback) {
    console.log('--------updateWeathers---------');

    //1. 删除之前天气
    deleteWeather(weatherList[0]['day']);

    //2. 更新未来五天天气
    weatherList.forEach(function (weather) {
        weathers.update({"day": weather.day}, {$set: weather}, {upsert: true}, function (err, result) {
            console.log(' --- err ----' + err);
            // console.log(' --- result ----' + result);
        });
    });

};

function deleteWeather(day, callback) {

    weathers.remove({'day': {$lt: day}}, function (err, result) {
        console.log(' --- err ----' + err);
        // console.log(' --- result ----' + result);
    });
};


// 获取天气
exports.getWeather = function (callback) {

    var res = {};

    weathers.find().toArray(function (err, result) {
        console.log("find err: " + err);
        // console.log("find result: " + result);
        // console.log("find length: " + result.length);
        if(err){
            res['id'] = 0;
        }else{
            res['id'] = 1;
            res['data'] = result;
        }
        callback(res);
    });

};



